
const http = require('http');
const url = require('url');
const fs = require('fs');
const qs = require('querystring');
const path = require('path');
const md5 = require("md5")
const hostname = "127.0.0.1";
const port = 8000;
let show = {
    1: {
        id: "1",
        number: 1,
        img: "../imgs/sp1.jpg",
        title: "统一来一桶老坛酸菜牛肉面 120g*3+红烧牛肉面 105g*3泡面组合",
        price: 23.0,
    },
    2: {
        id: "2",
        number: 1,
        img: "../imgs/sp2.jpg",
        title: "SELECTMOCA日本直邮2020年新品翻领机车夹克羊羔绒厚外套女",
        price: 568.0,
    },
    3: {
        id: "3",
        number: 1,
        img: "../imgs/sp3.jpg",
        title: "康夫电吹风机大功率发型师理发店专用电风吹负离子护发家用风筒",
        price: 118.0,
    },
    4: {
        id: "4",
        number: 1,
        img: "../imgs/sp4.jpg",
        title: "权志龙YGESHOP BIGBANG 棒球夹克 - Heidenei",
        price: 1111.0,
    },
    5: {
        id: "5",
        number: 1,
        img: "../imgs/sp5.jpg",
        title: "Huawei/华为 Mate 40 pro 5G手机官方旗舰店正品mate40pro+新p40直降mate50保时捷M40",
        price: 7999.0,
       
    },
    6: {
        id: 6,
        number: 1,
        img: "../imgs/sp6.jpg",
        title: "百草味 手撕面包1kg全麦整箱早餐饼干网红蛋糕点心礼盒装零食小吃",
        price: 59.9,
    },
    7: {
        id: "7",
        number: 1,
        img: "../imgs/sp7.jpg",
        title: "CANADA GOOSE / 加拿大鹅 Garson 马甲 4151M",
        price: 3099.0,
    },
    8: {
        id: "8",
        number: 1,
        img: "../imgs/sp8.jpg",
        title: "韩宇同款【经典款】Timberland添柏岚踢不烂男防水黄靴",
        price: 1490.0,
    },
    9: {
        id: "9",
        number: 1,
        img: "../imgs/sp9.jpg",
        title: "Apple/苹果 iPhone 12",
        price: 6299.0,
    },
    10: {
        id: "10",
        number: 1,
        img: "../imgs/sp10.jpg",
        title: "四川爱媛38号果冻橙10斤装橙子新鲜当季水果整箱柑橘蜜桔子包邮甜",
        price: 22.9,
    },
    11: {
        id: "11",
        number: 1,
        img: "../imgs/sp11.jpg",
        title: "联想无线运动型跑步蓝牙耳机双耳颈挂脖入耳挂耳头戴式单超长待机续航适用苹果x安卓8小米vivo华为oppo通用11",
        price: 169.0,
      
    },
    12: {
        id: "12",
        number: 1,
        img: "../imgs/sp12.jpg",
        title: "小米充电宝移动电源10000毫安快充超薄小巧便携大容量迷你18w高速 ",
        price: 79.0,
    },
};


let cart = [];
let users = new Map(); 
const server = http.createServer((req, res) => {
    let datas = "";
    req.on('error', (err) => {
        console.error(err);
    }).on('data', (chunk) => {
        datas += chunk;
    }).on('end', () => {
        res.statusCode = 200; 
        res.setHeader('Content-Type', 'text/html;charset=UTF-8'); 
        res.setHeader("Access-Control-Allow-Origin", "*"); 
        let curl = new url.URL(req.url, `http://${hostname}:${port}`);
        if (req.method === "POST") {
        } else if (req.method === "GET") {
            datas = curl['searchParams'].toString()
        } else {
            console.log(req.method, ":这个方法的处理暂未考虑。");
            pipe404(res);
            return;

        }
        switch (curl.pathname) {
            case "/":
                req.url = "/html/index.html";
                handleAsFile(req, res, req.url)
                break;
            case "/favicon.ico":
                req.url = "/../shopCart/src/imgs/favicon.ico";
                handleAsFile(req, res, req.url);
                break;

            case "/html/product_details.html":          
                res.setHeader('Set-Cookie', `${datas}`);       
                handleAsFile(req, res, curl.pathname);
                break;
            case "/getSKU":
                res.statusCode = 200;
                let dataId = datas.split('=')[1]
                if (show.hasOwnProperty(dataId)) {
                    res.end(`${JSON.stringify(show[dataId])}`)
                }
                break;

            case "/showCart": 
                let datas1 = JSON.parse(datas);
                if (ifLogin().sessionid != undefined) {
                    cart.push(datas1);
                    let Cart1 = getResultCart();
                    (users.get(ifLogin().username).cartInfo) = [...Cart1]
                    console.log(users)
                }
                res.statusCode = 200;
                res.end();
                break;
            case "/getCart":
                let Cart = getResultCart();
                res.writeHead(200, {
                    'Content-Type': 'text/json:charset=UTF-8'
                });
                if (ifLogin().sessionid != undefined) {
                    res.end(JSON.stringify(Cart));
                }
                break;
            case "/updateCart":
                res.writeHead(200, {
                    'Content-Type': 'text/json:charset=UTF-8'
                });
                cart = [...JSON.parse(datas)]
                res.end(JSON.stringify(datas));
                break;
            case "/reg":
                let userReg = JSON.parse(datas); 
                userReg.pwdMD5 = md5(userReg.pwdMD5);
                let sessionId = md5(userReg.name + (new Date()).getTime()).toUpperCase()
                if (users.has(userReg.name)) {
                    res.writeHead(200, {
                        'Content-Type': 'text/json:charset=UTF-8'
                    });
                    res.end('{"code":"4","msg":"用户已存在，请去登录"}'); 
                } else {
                    users.set(userReg.name, {
                        sessionid: sessionId,
                        userInfo: userReg,
                        cartInfo: []
                    });
                    res.writeHead(200, {
                        'Content-Type': 'text/json:charset=UTF-8',
                    });
                    res.end('{"code":"2","msg":"注册成功,请去登录"}');
                }
                break;

            case "/login":
                let userLogin = JSON.parse(datas); 
                userLogin.pwdMD5 = md5(userLogin.pwdMD5);
                let sessionID = md5(userLogin.name + (new Date()).getTime()).toUpperCase()
                if (users.has(userLogin.name) && users.get(userLogin.name).userInfo.pwdMD5 === userLogin.pwdMD5) {
                    let exp = new Date()
                    exp.setTime(exp.getTime() + 24 * 60 * 60 * 1000)
                    res.writeHead(200, {
                        'Content-Type': 'text/json:charset=UTF-8',
                        'Set-Cookie': ['sessionid=' + sessionID + ';expires=' + exp.toGMTString(), 'username=' + userLogin.name + ';expires=' + exp.toGMTString()]
                    });
                    users.get(userLogin.name).sessionid = sessionID;
                    res.end(JSON.stringify({
                        "code": 2,
                        "msg": users.get(userLogin.name)
                    })); 


                } else {
                    if (users.has(userLogin.name)) {
                        res.writeHead(200, {
                            'Content-Type': 'text/json:charset=UTF-8',
                        });
                        res.end(JSON.stringify({
                            "code": 1,
                            "msg": '密码错误'
                        }));       
                    } else {  
                        res.writeHead(200, {
                            'Content-Type': 'text/json:charset=UTF-8',
                        });
                        res.end(JSON.stringify({
                            "code": 5,
                            "msg": '没有该用户'
                        }));
                    }
                }
                break;
            case "/logout":
                let out = JSON.parse(datas);
                res.writeHead(200, {
                    'Content-Type': 'text/json:charset=UTF-8',             
                    'Set-Cookie': ['sessionid=' + users.get(out).sessionid + ';Max-Age=0', 'username=' + out.name + ';Max-Age=0']
                });

                res.end('成功登出');
                break;
            default:
                handleAsFile(req, res, curl.pathname);
                break;
        }     
        function ifLogin() {
            let Cookies = {}
            req.headers.cookie && req.headers.cookie.split(';').forEach((Cookie) => {
                if (!Cookie) {
                    return;
                }
                let parts = Cookie.split('=');
                Cookies[parts[0].trim()] = (parts[1] || '').trim()
            });
            return Cookies;
        }
    }) 


})
server.listen(port, hostname, () => {
    console.log(`服务器运行在 http://${hostname}:${port}/`);
})



function handleAsFile(req, res, pathname) {
    let f = __dirname + '/../shopCart/src' + pathname;
    fs.stat(f, (err, stat) => {
        if (err) {
            console.log(err);
            pipe404(res);
        } else {
            if (stat.isFile()) {
                setContentType(res, path.extname(pathname));
                fs.createReadStream(f).pipe(res);
            } else {
                pipe404(res);
            }
        }
    });
}

function getContentType(ext) {
    const extTypes = {
        ".html": "text/html",
        ".js": 'application/x-javascript',
        ".json": 'application/json', 
        ".*": 'application/octet-stream', 
        ".css": "text/css",
        ".png": "image/png",
        ".jpg": "application/x-jpg",
        ".jpeg": "image/jpeg",
        ".ico": "application/x-ico",
        ".gif": "image/gif"
    }
    if (ext == '') ext = ".*";
    let type = extTypes[ext];

    if (!type) {
        console.log(ext, "扩展名对应的数据类型未查到！");
        1
        type = 'application/octet-stream';
    }
    return type;
}

function setContentType(res, ext) {
    res.setHeader('Content-Type', getContentType(ext));
}

function pipe404(res) {
    res.statusCode = 404;
    res.setHeader('Content-Type', 'text/html;charset=UTF-8');
    res.end("<h1 style='color:red;'>404:请求内容不存在或服务暂不支持！</h1>");
}
function getResultCart() {
    let result = {};
    for (let i = 0, len = cart.length; i < len; i++) {
        let dataArr = cart[i];
        if (result[dataArr.id]) {
            result[dataArr.id].number++
        } else {
            result[dataArr.id] = {
                ...dataArr,
            };
        }
    }
    let resultCart = []; 
    for (const key in result) {
        resultCart.push(result[key]);
    }
    return resultCart;
}